const { key } = require("../config/default");
const { query } = require("../db/mysql");
const {
  queryUserByUsernameAndPassword,
  queryUserByTel,
  updateCodeByTel,
  queryUserByTelAndTelCode,
} = require("../utils");
const JWT = require("jsonwebtoken");
const router = require("koa-router")();

router.post("/login", async (ctx) => {
  //1. 获取用户名和密码
  const { username, password } = ctx.request.body;
  // 2. 查询数据库
  const result = await queryUserByUsernameAndPassword(username, password);
  // 3. 返回结果
  if (result) {
    const userInfo = { ...result };
    ctx.body = {
      code: 200,
      message: "登录成功",
      data: {
        userInfo: userInfo,
        token: JWT.sign(userInfo, key),
      },
    };
  } else {
    ctx.body = {
      code: 400,
      message: "账户密码错误， 请重新登录",
    };
  }
});

router.post("/login/tel", async (ctx) => {
  //1. 获取手机号
  const { tel, telCode } = ctx.request.body;
  // 2. 查询数据库
  const result = await queryUserByTelAndTelCode(tel, telCode);
  // 3. 返回结果
  if (result) {
    const userInfo = { ...result };
    ctx.body = {
      code: 200,
      message: "登录成功",
      data: {
        userInfo: userInfo,
        token: JWT.sign(userInfo, key),
      },
    };
  } else {
    ctx.body = {
      code: 400,
      message: "手机号或验证码不正确， 请重新登录",
    };
  }
});

router.get("/login/code", async (ctx) => {
  const { tel } = ctx.query;

  const result = await queryUserByTel(tel);

  if (result) {
    const randomCode = Math.random().toString(36).substr(2, 4);
    updateCodeByTel(tel, randomCode);
    ctx.body = {
      code: 200,
      message: "获取验证码成功",
      data: randomCode,
    };
  } else {
    ctx.body = {
      code: 400,
      message: "手机号未注册",
    };
  }
});
module.exports = router;
